<?php

namespace App\Http\Controllers\Api;

use App\Models\BookList;
use Illuminate\Http\Request;

class BookListController extends BaseController
{
    public function index(Request $request)
    {
        $page      = intval($request->get('page',1));
        $page      = max($page ,1);
        $page_size = intval($request->get('page_size',10));

        $columns = ['id','title','list_image'];
        $list = BookList::query()->with(['books'])->where('deleted',0)->orderBy('sort','asc')->paginate($page_size,$columns,'page',$page);

        $items = [];
        if(!empty($list))
        {
            foreach ($list as $v)
            {
                $items[] = [
                    'id'         => $v->id,
                    'title'      => $v->title,
                    'list_image' => $v->list_image,
                    'book_num'   => count($v->books)
                ];
            }
        }

        $top_image = \Redis::get('book-shop:book-list:top-image');
        $top_image = $top_image ? $top_image : '';

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items"     => $items,
            "top_image" => $top_image
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function show(Request $request)
    {
        $id = intval($request->get('id'));
        if(empty($id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $info = BookList::query()->with('books')->where('id',$id)->where('deleted',0)->first();
        if(empty($info))
        {
            return $this->err(1,200,'','书单不存在');
        }

        $items = [];
        if(!empty($info->books))
        {
            foreach ($info->books as $v)
            {
                $items[] = [
                    'book_id'           => $v->id,
                    'image'             => $v->image,
                    'title'             => $v->title,
                    'author'            => $v->author,
                    'score'             => $v->score,
                    'comment_num'       => $v->comment_num,
                    'message'           => $v->pivot->message,
                ];
            }
        }

        $result = [
            'id'           => $id,
            'title'        => $info->title,
            'detail_image' => $info->detail_image,
            'books_num'    => count($items),
            'items'        => $items,
        ];

        return $this->ok($result);
    }


}
